package com.ruoyi.common.net.mqtt.test;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.Date;

/**
 * @author xumh
 * @title: MqttSubscriber
 * @description: TODO
 * @date 2024/12/1815:05
 */
public class MqttSubscriber {
    private MqttClient mqttClient;

    public MqttSubscriber(String SERVER_URI, String CLIENT_ID) {
        try {
            MemoryPersistence persistence = new MemoryPersistence();
            this.mqttClient = new MqttClient(SERVER_URI, CLIENT_ID, persistence);
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName("");
            options.setPassword("".toCharArray());
            options.setConnectionTimeout(30);
            options.setAutomaticReconnect(true);
            options.setCleanSession(true);
            this.mqttClient.connect(options);
            System.out.println("链接成功********************");
        } catch (Exception var5) {
            var5.printStackTrace();
        }

    }

    public void unsubscribe(String topic) {
        if (this.mqttClient != null) {
            try {
                this.mqttClient.unsubscribe(topic);
            } catch (MqttException var3) {
                var3.printStackTrace();
            }

        }
    }

    public void subscribe(String topic) {
        if (this.mqttClient != null) {
            try {
                this.mqttClient.subscribe(topic);
                this.mqttClient.setCallback(new MqttCallback() {
                    public void connectionLost(Throwable throwable) {
                        System.out.println("连接丢失");
                    }

                    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                        System.out.println(topic);
                        System.out.println(mqttMessage.toString());
                    }

                    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                        System.out.println("delivery isComplete:" + iMqttDeliveryToken.isComplete());
                    }
                });
            } catch (MqttException var3) {
                System.out.println(var3.getMessage());
            }

        }
    }

    public static void main(String[] args) {
        String serverURI = "tcp://127.0.0.1:1883";
        String clientID = "demo_mqtt000000001" + (new Date()).getTime();
        MqttSubscriber mqttSubscriber = new MqttSubscriber(serverURI, clientID);
        mqttSubscriber.subscribe("test_topic");
    }
}

